# -*- coding: utf-8 -*-

import requests,re, json, time,os
from manage.exception import Exceptions
from base_config import  *


class ShopInfo( object  ):

    def __init__(self):

        self.pattern = re.compile(r"window.rawData= ({.*})")

        self.anti = 'mallName'

    def getPage(self, goods_id):

        r = requests.get( url = domain_url['other']['pdd_shop_url'].format( goods_id ) , headers=header )


        if r.status_code == 200 and self.anti in r.text :

            return r.text

        if r.status_code == 200 and self.anti not in r.text:

            print('[店铺信息采集任务]: IP被检测 等待程序重新执行:%s'%(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))

            return False

    def parseJson(self,params):

        goods_id = params['goodsid']

        html = self.getPage( goods_id )

        try:

            items = json.loads( re.search( self.pattern, html ).group(1) )

            data = items['store']['initDataObj']['mall']

            shopinfo = {

                'shopid':data['mallID'],
                'shopname':data['mallName'],
                'salesvolume':"0",
                'salesamount':"0",
                'goodsnum':"0"
            }

            self.aipRequest( shopinfo )

            #返回任务成功

            suData = {

                'id':params['tasksid']
            }

            Exceptions.successTask( suData )

        except:

            # 任务抓取失败 上传服务器
            failData = {
                'id':params['tasksid'],
                'msg':'店铺信息采集任务'
            }


            Exceptions.failTask( failData )

            # 退出
            os._exit(0)

    def aipRequest(self,data):

        r = requests.post( url = domain_url['domain']['test_shop_url'], data = data )

        if r.status_code == 200:

            print('[店铺信息采集任务]: 店铺信息上传成功:',data['shopname'])

        return None



if __name__ == '__main__':

    s = ShopInfo()

    data = {'tasksid': '1', 'sortby': None, 'addby': None, 'createtime': '2019-08-21 10:46:05', 'editby': None, 'edittime': None, 'type': '5', 'keywords': None, 'classcode': None, 'goodsid': '2045282', 'task_start_time': None, 'task_end_time': None, 'status': '0', 'recordscount': None, 'memo': '善存佳维片1.33g/片*60片【补充21种维生素】钙铁锌硒 远离亚健康', 'page': '0', 'processcode': '4A0EB47B-79D9-D7F4-7DE0-A7BC162013CC'}

    s.parseJson( data )
